import axios from 'axios';

// 登录接口
export const login = async (username, password) => {
  try {
    const response = await axios.post('/media/auth/login', {
      username,
      password
    });
    
    if (response.data) {
      // 保存token到sessionStorage
      sessionStorage.setItem('Authorization', `Bearer ${response.data.access_token}`);
      sessionStorage.setItem('refresh_token', response.data.refresh_token);
      sessionStorage.setItem('user_info', JSON.stringify(response.data.user_info));
      sessionStorage.setItem('token_expires_in', response.data.expires_in);
      sessionStorage.setItem('token_created_at', Date.now().toString());
      
      return response.data;
    }
  } catch (error) {
    console.error('登录失败:', error);
    throw error;
  }
};

// 检查用户是否已登录
export const isLoggedIn = () => {
  const token = sessionStorage.getItem('Authorization');
  const tokenCreatedAt = sessionStorage.getItem('token_created_at');
  const expiresIn = sessionStorage.getItem('token_expires_in');
  
  if (!token || !tokenCreatedAt || !expiresIn) {
    return false;
  }
  
  // 检查token是否过期
  const now = Date.now();
  const tokenAge = now - parseInt(tokenCreatedAt);
  const tokenExpiresInMs = parseInt(expiresIn) * 1000;
  
  if (tokenAge >= tokenExpiresInMs) {
    // token已过期，清除存储的信息
    logout();
    return false;
  }
  
  return true;
};

// 获取用户信息
export const getUserInfo = () => {
  const userInfoStr = sessionStorage.getItem('user_info');
  if (userInfoStr) {
    try {
      return JSON.parse(userInfoStr);
    } catch (error) {
      console.error('解析用户信息失败:', error);
      return null;
    }
  }
  return null;
};

// 登出
export const logout = () => {
  sessionStorage.removeItem('Authorization');
  sessionStorage.removeItem('refresh_token');
  sessionStorage.removeItem('user_info');
  sessionStorage.removeItem('token_expires_in');
  sessionStorage.removeItem('token_created_at');
};

// 刷新token
export const refreshToken = async () => {
  try {
    const refreshToken = sessionStorage.getItem('refresh_token');
    if (!refreshToken) {
      throw new Error('没有refresh token');
    }
    
    const response = await axios.post('/media/auth/refresh', {
      refresh_token: refreshToken
    });
    
    if (response.data) {
      // 更新token
      sessionStorage.setItem('Authorization', `Bearer ${response.data.access_token}`);
      sessionStorage.setItem('refresh_token', response.data.refresh_token);
      sessionStorage.setItem('token_expires_in', response.data.expires_in);
      sessionStorage.setItem('token_created_at', Date.now().toString());
      
      return response.data;
    }
  } catch (error) {
    console.error('刷新token失败:', error);
    logout();
    throw error;
  }
}; 